#!/usr/bin/env python
# @file environment.py


import os
import pwd

from object import List, Object, Readonly
from orders import ORDERS

class Path(List):
    def __init__(self, path='/usr/bin:/bin'):
        list.__init__(self, self.from_colon_fmt(path))

    def __add__(self, directory):
        self._type_check(directory)
        list.__add__(self, directory)

    def __setitem__(self, idx, directory):
        self._type_check(directory)
        list.__setitem__(self, idx, directory)

    def __repr__(self):
        the_str = "'"
        if len(self) > 0:
            the_str += str(self[0])
        for i in self[1:]:
            the_str += ":" + str(i)
        the_str += "'"
        return the_str

    def _type_check(self, obj):
        if not isinstance(item, Directory):
            raise TypeError, _('Only Directory instances may be \
added to env:PATH')

    def from_colon_fmt(self, path):
        return [Directory(d) for d in path.split(':')]

    def to_colon_fmt(self, path):
        return ':'.join(path)

class Environment(Readonly):
    _INIT = (
        ('UID', Readonly, os.getuid()),
        ('EUID', Readonly, os.geteuid()),
        ('PWD', Object, os.getcwdu()),
        ('prompt', Object, '; '),
    )

    def __init__(self, env=os.environ):
        for k, ctor, v in self._INIT:
            self[k] = ctor(v)

        self['orders'] = Object(items=ORDERS)

        for k, v in env.items():
            if k not in self:
                self[k] = Object(v)

        pwent = pwd.getpwuid(self['UID'].value)

        if 'HOME' not in self:
            self['HOME'] = pwent.pw_dir

        if 'USER' not in self:
            self['USER'] = pwent.pw_name

    def __setitem__(self, key, value):
        Readonly.__setitem__(self, key, value)
        os.putenv(key, str(value))

    def __delitem__(self, key):
        Readonly.__delitem__(self, key)
        os.unsetenv(key)
